import asyncio
from playwright.async_api import async_playwright
from typing import Optional

class TiktokUrl:
    @staticmethod
    async def from_dlpanda(tiktok_url: str) -> Optional[str]:
        async with async_playwright() as p:
            # ✅ 启动浏览器
            browser = await p.chromium.launch(
                headless=True,
                executable_path="/usr/bin/chromium"
            )
            context = await browser.new_context(
                user_agent=(
                    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
                    "AppleWebKit/537.36 (KHTML, like Gecko) "
                    "Chrome/118.0.5993.70 Safari/537.36"
                ),
                viewport={"width": 1920, "height": 1080},
                locale="en-US",
            )
            page = await context.new_page()

            third_party_url = "https://dlpanda.com/"
            print(f"🌐 打开页面: {third_party_url}")
            await page.goto(third_party_url, timeout=60000)

            # 等待输入框和按钮出现
            print("⏳ 等待输入框和下载按钮加载...")
            for i in range(30):  # 最多等 30 秒
                input_box = await page.query_selector("input[name='url']")
                submit_btn = await page.query_selector("button.one-click")
                if input_box and submit_btn:
                    print("✅ 检测到输入框和按钮")
                    break
                await asyncio.sleep(1)
            else:
                print("❌ 未检测到输入框或按钮")
                await browser.close()
                return None

            # 输入 TikTok 链接
            await input_box.fill(tiktok_url)
            print(f"📩 已输入链接: {tiktok_url}")

            # 点击下载按钮
            await submit_btn.click()
            print("🚀 已点击下载按钮，等待响应...")

            # ✅ 等待视频标签出现，而不是整页加载
            video_url = None
            for i in range(40):  # 最多重试 40 次（约 40 秒）
                video_el = await page.query_selector("video source[src]")
                if video_el:
                    video_url = await video_el.get_attribute("src")
                    if video_url:
                        print(f"🎬 成功提取视频地址: {video_url}")
                        break
                await asyncio.sleep(1)
            else:
                print("⚠️ 未找到视频地址")

            await browser.close()
            return video_url